<script setup>
const urlHome = useUrl();
const products = ref([]);
const productId = ref(0);
const isOpenSection = ref(false);
const isOpenProduct = ref(false);
const isOpenContract = ref(false);
const sectionName = ref('');
const productName = ref('');
const username = useCookie('username');
const prodSectionSelectId = ref(0);
const sectionError = ref('');
const productError = ref('');
const omsFull = ref('');
const omsBalance = ref('');
const obFull = ref('');
const obBalance = ref('');
const pdFull = ref('');
const pdBalance = ref('');
// const contractProdList = ref([]);
const contractSelect = ref(0);
const contractListSelect = ref([]);
const measureName = ref('');
const warehouse = ref('');
// const updateData = ref(false);

const prodSectionSelect = computed(() => prodSections.value.find(obj => obj.id === prodSectionSelectId.value))
const prodSelect = computed(() => products.value.find(obj => obj.id === productId.value))

const filterInput = (event) => {
	console.log(event.target.value)
	let newValue = event.target.value.replace(/[^0-9.-]/g, '');

	// Разрешаем минус только на первой позиции
	if (newValue.indexOf('-') > 0) {
		newValue = newValue.replace(/-/g, '');
	}
	console.log(newValue)

	// Разрешаем только одну точку
	const parts = newValue.split('.');
	if (parts.length > 2) {
		newValue = parts[0] + '.' + parts.slice(1).join('');
	}
	console.log(newValue)

	// Если начинается с точки, добавляем 0 перед ней
	if (newValue.startsWith('.')) {
		newValue = '0' + newValue;
	}
	console.log(newValue)
	warehouse.value = newValue;
};


const { data: prodSections, refresh: prodSecRefresh } = await useFetch(`${urlHome.value}orders/product_sections/`);

async function getProdList(section_id) {
	prodSectionSelectId.value = section_id
	productId.value = 0
	const response = await $fetch(`${urlHome.value}orders/products/`, {
		query: {
			section_id: section_id
		}
	})
	if (response) {
		products.value = response
	}
}

// const { data: contractProd, execute: getContractsProd } = await useFetch(`${urlHome.value}orders/product_contracts/`, {
// 	immediate: false,
// 	query: {
// 		product_id: productId
// 	},
// 	watch: [productId]
// })

// watchEffect(() => {
// 	console.log("updateData:", updateData.value);
// 	debugger
// 	updateData.value = false;
// 	prodSecRefresh();
// 	// getContractsProd();
// })

async function addSection() {
	const response = await $fetch(`${urlHome.value}orders/product_section_add/`, {
		method: 'POST',
		body: {
			section_name: sectionName.value,
			username: username.value,
		}
	})
	if (response.ok) {
		console.log(response)
		isOpenSection.value = false;
		sectionName.value = '';
		prodSecRefresh();
	} else if (response.status === 201) {
		sectionError.value = "Такой раздел уже есть"
	}
}

async function addProduct() {
	const response = await $fetch(`${urlHome.value}orders/product_add/`, {
		method: 'POST',
		body: {
			section_id: prodSectionSelect.value.id,
			product_name: productName.value,
			username: username.value,
			measure: measureName.value,
			warehouse: warehouse.value,
		}
	})
	if (response.ok) {
		isOpenProduct.value = false;
		productName.value = '';
		getProdList(prodSectionSelect.value.id);
	} else if (response.status === 201) {
		productError.value = 'Такой продукт уже есть'
	}
}

async function addContractProduct() {
	const response = await $fetch(`${urlHome.value}orders/contract_product_add/`, {
		method: 'POST',
		body: {
			oms_full: omsFull.value,
			oms_balance: omsBalance.value,
			ob_full: obFull.value,
			ob_balance: obBalance.value,
			pd_full: pdFull.value,
			pd_balance: pdBalance.value,
			product_id: productId.value,
			contract_id: contractSelect.value,
			username: username.value,
		}
	})
	if (response) {
		console.log("addContractProduct")
		omsFull.value = ''
		omsBalance.value = ''
		obFull.value = ''
		obBalance.value = ''
		pdFull.value = ''
		pdBalance.value = ''
		contractSelect.value = 0
		isOpenContract.value = false
		// getContractsProd()
	}
}

async function openContractModal() {
	await getContracts()
	isOpenContract.value = true

}

async function getContracts() {
	const response = await $fetch(`${urlHome.value}orders/get_contract_select/`, {
		query: {
			product_id: productId.value,
		}
	})
	if (response) {
		contractListSelect.value = response
	}
}

</script>
<template>
	<div>
		<div class="flex flex-col gap-2">
			<div class="flex flex-row gap-1" v-auto-animate>
				<UButton label="Добавить Группу" color="blue" @click="isOpenSection = true" />
				<div v-for="section in prodSections" :key="section.id">
					<div>
						<UButton color="violet" @click="getProdList(section.id)">{{ section.name }}</UButton>
					</div>
				</div>
			</div>
			<div class="flex flex-row gap-1" v-auto-animate>
				<div v-if="prodSectionSelectId > 0">
					<UButton color="blue" @click="isOpenProduct = true">Добавить продукт в раздел {{
						prodSectionSelect.name }}</UButton>
				</div>
				<div v-for="prod in products" :key="prod.id">
					<UButton @click="productId = prod.id"> {{ prod.name }}</UButton>
				</div>
			</div>
		</div>
		<div class="flex flex-col py-2" v-auto-animate v-if="productId > 0">
			<UButton class="max-w-48" color="blue" @click="openContractModal">
				Добавить договор к продукту {{ prodSelect.name }}</UButton>
			<PbStockContracts :productId="productId" />
		</div>
		<UModal v-model="isOpenSection">
			<UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
				<template #header>
					<div class="flex items-center justify-between">
						<h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
							Добавить группу продуктов
						</h3>
						<UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1"
							@click="isOpenSection = false" />
					</div>
				</template>

				<div>
					<div>
						<label>Название:</label>
						<UInput v-model="sectionName" @keyup.enter="addSection" />
					</div>
					<div class="text-red-600 font-bold">{{ sectionError }}</div>
					<div class="py-2">
						<UButton label="Добавить" @click="addSection" />
					</div>
				</div>
			</UCard>

		</UModal>
		<UModal v-model="isOpenProduct">
			<UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
				<template #header>
					<div class="flex items-center justify-between">
						<h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
							Добавить Продукт
						</h3>
						<UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1"
							@click="isOpenProduct = false" />
					</div>
				</template>

				<div>
					<div>
						<label>Название:</label>
						<UInput v-model="productName" />
					</div>
					<div>
						<label>Единицы измерения:</label>
						<UInput v-model="measureName" />
					</div>
					<div>
						<label>Остаток на складе:</label>
						<UInput v-model.lazy="warehouse" @keyup.enter="addProduct" @input="filterInput"
							placeholder="Введите число" />
					</div>
					<div class=" text-red-600 font-bold">{{ productError }}
					</div>
					<div class="py-2">
						<UButton label="Добавить" @click="addProduct" />
					</div>
				</div>
			</UCard>
		</UModal>
		<UModal v-model="isOpenContract">
			<UCard :ui="{ ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }">
				<template #header>
					<div class="flex items-center justify-between">
						<h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
							Добавить Договор
						</h3>
						<UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1"
							@click="isOpenContract = false" />
					</div>
				</template>
				<div>
					<div>
						<label>Договор:</label>
						<USelect v-model="contractSelect" :options="contractListSelect" option-attribute="name"
							value-attribute="id" />
					</div>
					<div class="py-2 text-right font-thin">
						Единицы измерения: {{ prodSelect.measure }}
					</div>
					<UDivider label="ОМС" />
					<div class="grid grid-cols-2 gap-2 py-2">
						<div class="flex flex-col">
							<label>Всего:</label>
							<UInput v-model="omsFull" />
						</div>
						<div class="flex flex-col">
							<label>Остаток:</label>
							<UInput v-model="omsBalance" />
						</div>
					</div>
					<UDivider label="ОБ" />
					<div class="grid grid-cols-2 gap-2 py-2">
						<div class="flex flex-col">
							<label>Всего:</label>
							<UInput v-model="obFull" />
						</div>
						<div class="flex flex-col">
							<label class="text-">Остаток:</label>
							<UInput v-model="obBalance" />
						</div>
					</div>
					<UDivider label="ПД" />
					<div class="grid grid-cols-2 gap-2 py-2">
						<div class="flex flex-col">
							<label>Всего:</label>
							<UInput v-model="pdFull" />
						</div>
						<div class="flex flex-col">
							<label>Остаток:</label>
							<UInput v-model="pdBalance" @keyup.enter="addContractProduct" />
						</div>
					</div>
					<div class="py-2">
						<UButton label="Добавить" @click="addContractProduct" />
					</div>
				</div>
			</UCard>
		</UModal>
	</div>
</template>